package games.catchTheCreature;


import java.util.ArrayList;
import java.util.HashMap;

import commonDataStructures.PSortedCollection;
import commonDataStructures.PrimitiveCollection;


public class CatchTheCreature {


	private CTCBoard _world;

	private CTCState _initState;

	public void printWorld(){
		_world.printWorld();
	}
	public CatchTheCreature(CTCBoard world){
		_world = world;
	}

	public CTCState getInitState(){
		return _initState;
	}

	public GameInfo playGame(PrimitiveCollection<CTCState> bank,int gamesNum){
		long explorer = 0;
		int totalStates = 0;
		int solDepth = 0;
		HashMap<String, String> usedStates = new HashMap<String, String>();
		for(int i=0;i<gamesNum;i++){
			Heuristic h = new Heuristic(_world);
			
			//toggeling to A*
			if (bank instanceof PSortedCollection){
				h.setAStart();
			}
			
			_initState = new CTCState(_world,false,0,h);
			bank.init();
			bank.insert(getInitState());
			CTCState nxt = bank.remove();
			usedStates.put(nxt.hash(), null);
			totalStates++;
			int tnodes = 0;
			while (!nxt.isWin()){
				//get next moves
				ArrayList<CTCState> tmp = nxt.getPossibleMoves();
				//take only the none encountered states
				for(CTCState s:tmp){
					if (!usedStates.containsKey(s.hash())){
						tnodes++;
						if (s.isWin()){
							bank.init();
							bank.insert(s);
							break;
						}
						bank.insert(s);
					}
				}
				nxt = bank.remove();
				explorer++;
			}
			solDepth+=nxt.getDepth();
			totalStates+=tnodes;
			//System.out.println("Game #"+i+" Total Memory: "+totalStates+" SolDepth: "+nxt.getDepth()+" Total nodes: "+explorer+" Time: "+(System.currentTimeMillis()-tStart));
		}
		return new GameInfo(totalStates/gamesNum,solDepth/gamesNum);

	}
}
